<?php

namespace app\service;

use app\core\exception\BusinessException;
use app\core\Service;
use app\model\LotusLamp;
use app\model\Temple;
use BaconQrCode\Encoder\QrCode;
use Endroid\QrCode\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Label\Alignment\LabelAlignmentCenter;
use Endroid\QrCode\Label\Font\NotoSans;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;

/**
 * @extends Service<QrCodeService>
 */
class QrCodeService extends Service
{
    public static function generateQrCode($url, $label = '', $size = 300, $margin = 10)
    {

        $qr = Builder\Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            ->data($url)
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->size($size)
            ->margin($margin)
            ->roundBlockSizeMode(new RoundBlockSizeModeMargin());
        if (!empty($label)) {
            $qr->labelText($label)
                ->labelFont(new NotoSans(20))
                ->labelAlignment(new LabelAlignmentCenter());
        }
        return $qr->build()->getDataUri();
    }

    public static function getCode($url, $label = '', $size = 300, $margin = 10)
    {
        $qr = Builder\Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            ->data($url)
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->size($size)
            ->margin($margin)
            ->roundBlockSizeMode(new RoundBlockSizeModeMargin());
        if (!empty($label)) {
            $qr->labelText($label)
                ->labelFont(new NotoSans(20))
                ->labelAlignment(new LabelAlignmentCenter());
        }
        return $qr->build()->getDataUri();
    }

    public function savePath($id)
    {
        $root = __DIR__ . "/../../public";
        $info = LotusLamp::where('id', $id)->find();
        if (empty($info)) {
            throw new BusinessException('数据不存在');
        }
        if ($info['image_url'] != '') {
            return $info['image_url'];
            $filePath = $root . $info['image_url'];
            if (file_exists($filePath)) {
                unlink($filePath);
            }
        }
        $path = '/storage/' . date('Ymd') . "/" . md5(time()) . '.png';
        $image_url = $root . $path;
        // 确保目录存在
        $directory = dirname($image_url);
        if (!is_dir($directory)) {
            mkdir($directory, 0755, true); // 第三个参数 true 表示可以创建多级目录
        }
        $appid = $this->app->config->get('app.app_id');
        $secret = $this->app->config->get('app.app_secret');
        $tokenAccessUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $access_token_json = file_get_contents($tokenAccessUrl);
        $access_token_array = json_decode($access_token_json, true);
        $access_token = $access_token_array['access_token'];
        //生成小程序码的API地址
        $qrcodeUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=$access_token";
        $param = [
            'path' => 'pages/pray/pray?temple_id=1&lotus_lamp_ids=' . $id, //小程序的页面路径
            'width' => 300,
        ];
        $postData = json_encode($param);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $qrcodeUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        $result = curl_exec($ch);
        curl_close($ch);
        file_put_contents($image_url, $result);
        $info->save(['image_url' => $path]);
        return $path;
    }


}